﻿using HandyControl.Controls;
using LOLApi;
using LOLApi.Models;
using Prism.Commands;
using Prism.Common;
using Prism.Mvvm;
using Prism.Regions;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Controls;

namespace Tryit.ViewModels
{
    public class RecordSearchViewModel : BindableBase, INavigationAware
    {

        private string _lefttextColor = "Black";
        public string LeftTextColor
        {
            get { return _lefttextColor; }
            set { SetProperty(ref _lefttextColor, value); }
        }
        private string _rightTextColor = "Black";
        public string RightTextColor
        {
            get { return _rightTextColor; }
            set { SetProperty(ref _rightTextColor, value); }
        }
        private int _page = 1;// 默认第一页;
        public int Page
        {
            get { return _page; }
            set { SetProperty(ref _page, value); }
        }
        /// <summary>
        /// 双方团队击杀
        /// </summary>
        private string _teamKill = "/";
        public string TeamKill
        {
            get { return _teamKill; }
            set { SetProperty(ref _teamKill, value); }
        }
        /// <summary>
        /// 比赛时长
        /// </summary>
        private string _gameTimeLength = "——";
        public string GameTimeLength
        {
            get { return _gameTimeLength; }
            set { SetProperty(ref _gameTimeLength, value); }
        }
        /// <summary>
        /// 游戏模式
        /// </summary>
        private string _gameMode = "——";
        public string GameMode
        {
            get { return _gameMode; }
            set { SetProperty(ref _gameMode, value); }
        }
        /// <summary>
        /// 游戏开始时间
        /// </summary>
        private string _gameStartTime = "——";
        public string GameStartTime
        {
            get { return _gameStartTime; }
            set { SetProperty(ref _gameStartTime, value); }
        }
        /// <summary>
        /// 当前用户名称
        /// </summary>
        private string _urrentSommonerName;
        public string CurrentSommonerName
        {
            get { return _urrentSommonerName; }
            set { SetProperty(ref _urrentSommonerName, value); }
        }
        /// <summary>
        ///  搜索框文本
        /// </summary>
        private string _searchText;
        public string Text
        {
            get { return _searchText; }
            set { SetProperty(ref _searchText, value); }
        }
        /// <summary>
        /// 列表选中item 
        /// </summary>
        private int _index;
        public int Index
        {
            get { return _index; }
            set { SetProperty(ref _index, value); }
        }

        /// <summary>
        /// leftteam选中item 
        /// </summary>
        private int _leftTeamIndex = -1;
        public int LeftTeamIndex
        {
            get { return _leftTeamIndex; }
            set { SetProperty(ref _leftTeamIndex, value); }
        }
        /// <summary>
        /// leftteam选中item 
        /// </summary>
        private int _rightTeamIndex = -1;
        public int RightTeamIndex
        {
            get { return _rightTeamIndex; }
            set { SetProperty(ref _rightTeamIndex, value); }
        }
        private string _showLoading = "Hidden";
        public string ShowLoading
        {
            get
            {
                return _showLoading;
            }
            set { SetProperty(ref _showLoading, value); }
        }
        private string _showGrid = "Hidden";
        public string ShowGrid
        {
            get { return _showGrid; }
            set { SetProperty(ref _showGrid, value); }
        }
        public bool DataHasLoaded { get; set; }
        public DelegateCommand PageUp { get => new DelegateCommand(Pageup); }
        public DelegateCommand PageDown { get => new DelegateCommand(Pagedown); }
        public DelegateCommand GameSelectionChangedCommandAsync { get => new DelegateCommand(SelectionChanged); }
        public DelegateCommand LeftTeamSelectedChangedCommandAsync { get => new DelegateCommand(LeftTeamSelectionChanged); }
        public DelegateCommand RightTeamSelectedChangedCommandAsync { get => new DelegateCommand(RightTeamSelectionChanged); }
        public DelegateCommand GoBackToSelf { get => new DelegateCommand(GoBackToCurrentSommoner); }

        public DelegateCommand<string> Search { get => new DelegateCommand<string>(SearchSumoner); }

        public ObservableCollection<Recordby20> DataList { get; set; } = new ObservableCollection<Recordby20>();

        public TeamData TeamData { get; set; } = new TeamData();

        private int pageSize = 10; // 每页10条数据
        public int Start => (Page - 1) * pageSize;
        public int End => Start + pageSize - 1;
        public string? Puuid { get; set; }
        public RecordSearchViewModel()
        {

        }
        private async Task LoadData(string puuid, int start, int end)
        {

            HttpClient LcuClient = new LcuClient()._httpClient;
            var championInfos = await GetInfo.GetChampionInfos(LcuClient);
            Matches matches = await GetInfo.GetMatchesAsync(LcuClient, puuid, start, end);//获取最近20场游戏记录
            var games = matches.games.games;
            DataList.Clear();
            foreach (var game in games)
            {
                Recordby20 match = new Recordby20();
                match.GameTime = DateTime.Parse(game.gameCreationDate).ToString("M");
                match.Outcome = game.participants[0].stats.win ? "胜利" : "失败";
                match.GameId = game.gameId;
                var champion = Account.Champions.FirstOrDefault(item => game.participants[0].championId == item.id);
                if (champion != null)
                {
                    match.Hero = champion.name;
                    match.HeroIcon = string.Format(Base.ChampionIcon, champion.alias);
                }
                match.GameType = GetGameType(game);
                match.ParticipantId = game.participants[0].participantId;
                // match.CombatGains = $"{game.participants[0].stats.kills}/{game.participants[0].stats.deaths}/{game.participants[0].stats.assists}";
                DataList.Add(match);
            }
        }
        private async void Pageup()
        {
            Page++;
            await LoadData(Puuid, Start, End);
            Index = 0;
        }
        private async void Pagedown()
        {
            Page--;
            if (Page <= 0) Page = 1;
            await LoadData(Puuid, Start, End);
            Index = 0;

        }
        private async void SearchSumoner(string SearchText)
        {
            HttpClient LcuClient = new LcuClient()._httpClient;
            if (!string.IsNullOrEmpty(SearchText))
            {
                var summoner = await GetInfo.GetPuuidByName(LcuClient, SearchText);
                if (summoner != null)
                {
                    Puuid = summoner.Puuid;
                    Page = 1;
                    await LoadData(Puuid, Start, End);
                    CurrentSommonerName = SearchText;
                    Index = 0;
                }
                else Growl.Warning("未查询到该召唤师！");
            }
            else Growl.Warning("召唤师名称不能为空！");
        }
        private async void SelectionChanged()
        {
            if (DataList.Count > 0)
            {
                HttpClient LcuClient = new LcuClient()._httpClient;
                Dictionary<int,string> dic = new Dictionary<int,string>();
                var detail = await GetInfo.GetMathesDetail(LcuClient, DataList[Index].GameId);
                GameStartTime = DateTime.Parse(detail.gameCreationDate).ToString("MM-dd HH:mm");
                GameMode = DataList[Index].GameType;
                GameTimeLength = detail.gameDuration / 60 + "分钟";
                string leftTeamKill = detail.participants.Where(item => item.teamId == 100).Select(item => new { kills = item.stats.kills }).Sum(item => item.kills).ToString();
                string RightTeamKill = detail.participants.Where(item => item.teamId == 200).Select(item => new { kills = item.stats.kills }).Sum(item => item.kills).ToString();
                string leftTeamDeath = detail.participants.Where(item => item.teamId == 100).Select(item => new { deaths = item.stats.deaths }).Sum(item => item.deaths).ToString();
                string RightTeamDeath = detail.participants.Where(item => item.teamId == 200).Select(item => new { deaths = item.stats.deaths }).Sum(item => item.deaths).ToString();
                string leftTeamAssists = detail.participants.Where(item => item.teamId == 100).Select(item => new { assists = item.stats.assists }).Sum(item => item.assists).ToString();
                string RightTeamAssists = detail.participants.Where(item => item.teamId == 200).Select(item => new { assists = item.stats.assists }).Sum(item => item.assists).ToString();
                TeamKill = leftTeamKill + "/" + RightTeamKill;
                TeamData.LeftWin = detail.teams[0].win;
                TeamData.RightWin = detail.teams[1].win;
                LeftTextColor = TeamData.LeftWin == "胜方" ? "#40B5C5" : "LightCoral";
                RightTextColor = TeamData.RightWin == "胜方" ? "#40B5C5" : "LightCoral";
                TeamData.LeftKillsAndDeathAndAssists = leftTeamKill + "/" + leftTeamDeath + "/" + leftTeamAssists;
                TeamData.RightKillsAndDeathAndAssists = RightTeamKill + "/" + RightTeamDeath + "/" + RightTeamAssists;
                TeamData.LeftTeamMoney = Math.Round((double)detail.participants.Where(item => item.teamId == 100).Select(item => new { gold = item.stats.goldEarned }).Sum(item => item.gold) / 1000, 2) + "k";
                TeamData.RightTeamMoney = Math.Round((double)detail.participants.Where(item => item.teamId == 200).Select(item => new { gold = item.stats.goldEarned }).Sum(item => item.gold) / 1000, 2) + "k";
                TeamData.LeftKillTower = detail.teams[0].towerKills.ToString();
                TeamData.RightKillTower = detail.teams[1].towerKills.ToString();
                TeamData.LeftKillinhibito = detail.teams[0].inhibitorKills.ToString();
                TeamData.RightKillinhibito = detail.teams[1].inhibitorKills.ToString();
                TeamData.LeftKillbaron = detail.teams[0].baronKills.ToString();
                TeamData.RightKillbaron = detail.teams[1].baronKills.ToString();
                TeamData.LeftKilldragon = detail.teams[0].dragonKills.ToString();
                TeamData.RightKilldragon = detail.teams[1].dragonKills.ToString();
                TeamData.LeftTeamDataDetail.Clear();
                TeamData.RightTeamDataDetail.Clear();
                foreach (var item in detail.participantIdentities)
                {
                    dic.Add(item.participantId, item.player.gameName + "#" + item.player.tagLine);
                }
                foreach (var participant in detail.participants.Where(item => item.teamId == 100))
                {   
                    TeamDataDetail dataDetail = new TeamDataDetail();
                    var champion = Account.Champions.FirstOrDefault(item => participant.championId == item.id);
                    if (champion != null) dataDetail.HeroIcon = string.Format(Base.ChampionIcon, champion.alias);
                    dataDetail.SummonerName = dic[participant.participantId];
                    dataDetail.Spell1Id = participant.spell1Id;
                    dataDetail.Spell2Id = participant.spell2Id;
                    dataDetail.Item0 = participant.stats.item0;
                    dataDetail.Item1 = participant.stats.item1;
                    dataDetail.Item2 = participant.stats.item2;
                    dataDetail.Item3 = participant.stats.item3;
                    dataDetail.Item4 = participant.stats.item4;
                    dataDetail.Item5 = participant.stats.item5;
                    dataDetail.Item6 = participant.stats.item6;
                    dataDetail.KDA = participant.stats.kills + "/" + participant.stats.deaths + "/" + participant.stats.assists;
                    dataDetail.Gold = Math.Round((double)participant.stats.goldEarned / 1000, 2) + "k";
                    dataDetail.Damage = Math.Round((double)participant.stats.totalDamageDealtToChampions / 1000, 2) + "k";
                    dataDetail.DamageToken = Math.Round((double)participant.stats.totalDamageTaken / 1000, 2) + "k";
                    dataDetail.IsCurrentSummonerName = CurrentSommonerName == dataDetail.SummonerName ? true : false;
                    TeamData.LeftTeamDataDetail.Add(dataDetail);
                }
                foreach (var participant in detail.participants.Where(item => item.teamId == 200))
                {
                    TeamDataDetail dataDetail = new TeamDataDetail();
                    var champion = Account.Champions.FirstOrDefault(item => participant.championId == item.id);
                    if (champion != null) dataDetail.HeroIcon = string.Format(Base.ChampionIcon, champion.alias);
                    dataDetail.SummonerName =  dic[participant.participantId];
                    dataDetail.Spell1Id = participant.spell1Id;
                    dataDetail.Spell2Id = participant.spell2Id;
                    dataDetail.Item0 = participant.stats.item0;
                    dataDetail.Item1 = participant.stats.item1;
                    dataDetail.Item2 = participant.stats.item2;
                    dataDetail.Item3 = participant.stats.item3;
                    dataDetail.Item4 = participant.stats.item4;
                    dataDetail.Item5 = participant.stats.item5;
                    dataDetail.Item6 = participant.stats.item6;
                    dataDetail.KDA = participant.stats.kills + "/" + participant.stats.deaths + "/" + participant.stats.assists;
                    dataDetail.Gold = Math.Round((double)participant.stats.goldEarned / 1000, 2) + "k";
                    dataDetail.Damage = Math.Round((double)participant.stats.totalDamageDealtToChampions / 1000, 2) + "k";
                    dataDetail.DamageToken = Math.Round((double)participant.stats.totalDamageTaken / 1000, 2) + "k";
                    dataDetail.IsCurrentSummonerName = participant.participantId == DataList[Index].ParticipantId ? true : false;
                    TeamData.RightTeamDataDetail.Add(dataDetail);
                }

            }

        }
        private void GoBackToCurrentSommoner()
        {
            if (Account.Summoner != null)
            {
                SearchSumoner(Account.Summoner.GameName + "#" + Account.Summoner.TagLine);
            }
        }

        private void RightTeamSelectionChanged()
        {
            if (TeamData.RightTeamDataDetail.Count > 0 && !TeamData.RightTeamDataDetail[RightTeamIndex].IsCurrentSummonerName)
            {
                SearchSumoner(TeamData.RightTeamDataDetail[RightTeamIndex].SummonerName);
            }
        }

        private void LeftTeamSelectionChanged()
        {
            if (TeamData.LeftTeamDataDetail.Count > 0 && !TeamData.LeftTeamDataDetail[LeftTeamIndex].IsCurrentSummonerName)
            {
                SearchSumoner(TeamData.LeftTeamDataDetail[LeftTeamIndex].SummonerName);
            }
        }
        private async Task InitData()
        {
            if (Account.Summoner != null && Account.Champions != null)
            {
                Puuid = Account.Summoner.Puuid;
                CurrentSommonerName = Account.Summoner.GameName + "#" + Account.Summoner.TagLine;
                await LoadData(Puuid, Start, End);
            }
        }
        private string GetGameType(MatchGames game)
        {
            switch (game.gameMode)
            {
                case "URF": return "无限火力";
                case "ARURF": return "无限乱斗";
                case "ARAM": return "大乱斗";
                case "CLASSIC":
                    return game.queueId switch
                    {
                        420 => "单双排",
                        430 => "匹配",
                        440 => "灵活排位",
                        _ => "其它"
                    };
                case "ULTBOOK": return "终极魔典";
                default: return "自定义";
            }
        }

        public async void OnNavigatedTo(NavigationContext navigationContext)
        {
            if (navigationContext.Parameters.ContainsKey("shouldReload"))
            {
                bool shouldReload = (bool)navigationContext.Parameters["shouldReload"];
                if (shouldReload)
                {
                    ShowLoading = "Visible";
                    ShowGrid = "Hidden";
                    await InitData(); // 重新加载数据的方法
                    Index = 0;
                    ShowLoading = "Hidden";
                    ShowGrid = "Visible";
                    DataHasLoaded = true;
                }
            }
            else
            {
                if (!DataHasLoaded)
                {
                    ShowLoading = "Visible";
                    ShowGrid = "Hidden";
                    await InitData(); // 重新加载数据的方法
                    ShowLoading = "Hidden";
                    ShowGrid = "Visible";
                    DataHasLoaded = true;
                }
            }
        }

        public bool IsNavigationTarget(NavigationContext navigationContext)
        {
            return true;
        }

        public void OnNavigatedFrom(NavigationContext navigationContext)
        {
            return;
        }
    }
}
